package android.storefront.common.utils.database;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import android.storefront.common.utils.properties.PropertiesUtil;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class InitailDatabaseData {
	
	private static InitailDatabaseData initailDatabaseData = new InitailDatabaseData();
	
	public static InitailDatabaseData getInstance(){
		return initailDatabaseData;
	}
	
	private SQLiteDatabase sqLiteDatabase = null;
	
	public void initialTable(String dataFileName,Context context){
		String name = PropertiesUtil.getInstance().getValue("databaseName");
		String tablePropertiesInsertSql = SqlitePropertiesUtil.getInstance().getValue(dataFileName+"_insert");
		List<String> list = getDataList(dataFileName);
		if(context.getDatabasePath(name).exists()){
			sqLiteDatabase = new DatabaseHelper(context, name).getWritableDatabase();
			try {
				sqLiteDatabase.beginTransaction();
				for(String s : list){
					String[] objs = s.split("#");
					sqLiteDatabase.execSQL(tablePropertiesInsertSql, objs);
				}
				sqLiteDatabase.setTransactionSuccessful();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				sqLiteDatabase.endTransaction();
				sqLiteDatabase.close();
			}
		}
		
	}
	
	private List<String> getDataList(String dataFileName){
		List<String> list = new ArrayList<String>();
		InputStreamReader inputStreamReader = null;
		LineNumberReader lineNumberReader = null;
		try {
			inputStreamReader = new InputStreamReader(InitailDatabaseData.class.getClassLoader().getResourceAsStream(dataFileName), "utf-8");
			lineNumberReader = new LineNumberReader(inputStreamReader);
			
			String cacheStr = null;
			while(true){
				cacheStr = lineNumberReader.readLine();
				if(null != cacheStr){
					list.add(cacheStr);
				}else{
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(null != inputStreamReader){
					inputStreamReader.close();
				}
				if(null != lineNumberReader){
					lineNumberReader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return list;
	}

}
